package com.gsm.phimhanhdong;

import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Locale;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.actionbarsherlock.app.SherlockFragment;
import com.google.analytics.tracking.android.EasyTracker;
import com.gsm.phimhanhdong.ContentNetworkInterface.ErrorConnectionEvent;
import com.gsm.phimhanhdong.ContentNetworkInterface.ErrorGetMoreVideoEvent;
import com.gsm.phimhanhdong.ContentNetworkInterface.ErrorGetPlaylistConnectionEvent;
import com.gsm.phimhanhdong.ContentNetworkInterface.GetBannerSuccessEvent;
import com.gsm.phimhanhdong.ContentNetworkInterface.GetListPlaylistSuccessEvent;
import com.gsm.phimhanhdong.ContentNetworkInterface.GetMorePlaylistVideoSuccess;
import com.gsm.phimhanhdong.ContentNetworkInterface.GetMoreVideoInfoSuccess;
import com.gsm.phimhanhdong.ContentNetworkInterface.GetPlaylistVideoFail;
import com.gsm.phimhanhdong.ContentNetworkInterface.GetPlaylistVideoSuccess;
import com.gsm.phimhanhdong.ContentNetworkInterface.GetPopUpSuccessEvent;
import com.gsm.phimhanhdong.ContentNetworkInterface.GetVideoInfoFail;
import com.gsm.phimhanhdong.ContentNetworkInterface.GetVideoInfoSuccess;
import com.gsm.phimhanhdong.ContentNetworkInterface.OnMenuItemClickEvent;
import com.gsm.phimhanhdong.ContentNetworkInterface.OnReload;
import com.gsm.phimhanhdong.ContentNetworkInterface.OptionMenuItemClickEvent;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;

import de.greenrobot.event.EventBus;

public class VideoFragment extends SherlockFragment implements
		com.gsm.phimhanhdong.LoadMoreListView.OnLoadMoreListener,
		OnMenuFragmentItemClickListenner {
	public static final int alarm_interval = 3 * 60 * 60 * 1000;
	public static final int alarm_interval_checkinstallApp = 3 * 24 * 60 * 60
			* 1000;
	public String playlist_id;
	LoadMoreListView listView;
	private ImageLoader imageLoader;
	private DisplayImageOptions options;
	private MyAdapter myAdapter;
	String chanel_name;
	Playlist playlist;
	private LinearLayout llLoading;
	private BackgroundTasks bgTask;
	Banner banner;
	private Banner popup;
	private View bannerLayout;
	private TextView txtLoad;
	private ProgressBar progressBar;
	Button reload;
	EventBus eventBus;

	private void initImageLoader() {
		imageLoader = ImageLoader.getInstance();
		options = new DisplayImageOptions.Builder()
				.showImageForEmptyUri(R.drawable.ic_launcher).cacheInMemory()
				.imageScaleType(ImageScaleType.IN_SAMPLE_INT).cacheOnDisc()
				.build();
		imageLoader.clearDiscCache();
		imageLoader.clearMemoryCache();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View view = inflater.inflate(R.layout.activity_main, null);
		llLoading = (LinearLayout) view.findViewById(R.id.llloading);
		txtLoad = (TextView) view.findViewById(R.id.txtLoad);
		progressBar = (ProgressBar) view.findViewById(R.id.progressbar);
		reload = (Button) view.findViewById(R.id.reload);
		reload.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				eventBus.post(new OnReload());
			}
		});
		initImageLoader();
		EventBus.getDefault().register(this);
		eventBus = EventBus.getDefault();
		bgTask = new BackgroundTasks(getActivity());
		listView = (LoadMoreListView) view.findViewById(R.id.listview);
		listView.setOnLoadMoreListener(this);
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				String videoid = (String) arg1.getTag();
				Intent intent = new Intent(getActivity(),
						PlayerViewDemoActivity.class);
				intent.putExtra("videoid", videoid);
				startActivity(intent);
				EasyTracker.getTracker()
						.sendEvent(Constants.EVENT, "click item video",
								"video " + videoid, Long.valueOf(1));
			}
		});
		bannerLayout = inflater.inflate(R.layout.banner_fragment, null);
		listView.addHeaderView(bannerLayout, null, false);
		return view;
	}

	public void onEventMainThread(GetPlaylistVideoSuccess e) {
		playlist = e.playlist;
		bgTask.getVideoInfo(e.playlist);
	}

	public void onEventMainThread(GetBannerSuccessEvent e) {
		Log.e("", "GetBannerSuccessEvent ");
		banner = e.banner;
		ImageView imageView = new ImageView(getActivity());
		listView.addHeaderView(imageView);
		imageLoader.displayImage(banner.url, imageView, options);
	}

	public void onEventMainThread(GetPopUpSuccessEvent e) {
		popup = e.banner;
	}

	public void onEventMainThread(GetMorePlaylistVideoSuccess e) {
		offset = playlist.getVideos().size();
		playlist.getVideos().addAll(e.playlist.getVideos());
		playlist.setNextPageToken(e.playlist.getNextPageToken());
		playlist.setPrevPageToken(e.playlist.getPrevPageToken());
		bgTask.getMoreVideoInfo(e.playlist);
	}

	public void onEventMainThread(OptionMenuItemClickEvent e) {
		Collections.sort(this.playlist.getVideos(), e.getComparator());
		myAdapter.notifyDataSetChanged();
	}

	int offset = 0;

	public void onEventMainThread(GetMoreVideoInfoSuccess e) {
		for (int i = offset; i < playlist.getVideos().size(); i++) {
			boolean tmp = false;
			for (int j = offset; j < e.infos.size(); j++) {
				if (playlist.getVideos().get(i).videoid
						.equals(e.infos.get(j).id)) {
					playlist.getVideos().get(i).videoinfo = e.infos.get(j);
					tmp = true;
				}
			}
			if (!tmp) {
				playlist.getVideos().remove(i);
				i--;
			}
			// playlist.getVideos().get(i).videoinfo = e.infos.get(i - offset);
		}
		myAdapter.notifyDataSetChanged();
		listView.onLoadMoreComplete();
	}

	public void onEventMainThread(GetVideoInfoFail e) {
		progressBar.setVisibility(View.GONE);
		txtLoad.setText(getResources().getString(R.string.loading_faill));
		reload.setVisibility(View.VISIBLE);
	}

	public void onEventMainThread(GetVideoInfoSuccess e) {
		for (int i = 0; i < playlist.getVideos().size(); i++) {
			boolean tmp = false;
			for (int j = offset; j < e.infos.size(); j++) {
				if (playlist.getVideos().get(i).videoid
						.equals(e.infos.get(j).id)) {
					playlist.getVideos().get(i).videoinfo = e.infos.get(j);
					tmp = true;
				}
			}
			if (!tmp) {
				playlist.getVideos().remove(i);
				i--;
			}
		}
		// getSupportActionBar().setTitle(title)
		myAdapter = new MyAdapter(getActivity(), playlist.getVideos());
		listView.setAdapter(myAdapter);
		listView.setVisibility(View.VISIBLE);
		llLoading.setVisibility(View.GONE);
	}

	public void onEventMainThread(GetListPlaylistSuccessEvent e) {
		llLoading.setVisibility(View.VISIBLE);
		progressBar.setVisibility(View.VISIBLE);
		reload.setVisibility(View.GONE);
		txtLoad.setText("Đang tải dữ liệu ");
		playlist_id = e.playlists.get(0).id;
		loadData(playlist_id);
	}

	private void loadData(String playlist_id) {
		// TODO Auto-generated method stub
		this.playlist_id = playlist_id;
		llLoading.setVisibility(View.VISIBLE);
		listView.setVisibility(View.GONE);
		reload.setVisibility(View.GONE);
		bgTask.getPlayListVideo(playlist_id);
	}

	public void onEventMainThread(GetPlaylistVideoFail e) {
		Log.e("", "ErrorGetPlaylistConnectionEvent");
		progressBar.setVisibility(View.GONE);
		txtLoad.setText("Tải dữ liệu thất bại ");
		reload.setVisibility(View.VISIBLE);
	}

	public void onEventMainThread(ErrorGetPlaylistConnectionEvent e) {
		Log.e("", "ErrorGetPlaylistConnectionEvent");
		progressBar.setVisibility(View.GONE);
		txtLoad.setText("Tải dữ liệu thất bại ");
		reload.setVisibility(View.VISIBLE);
	}

	public void onEventMainThread(ErrorConnectionEvent e) {
		Log.e("", "ErrorConnectionEvent");
		progressBar.setVisibility(View.GONE);
		reload.setVisibility(View.VISIBLE);
		txtLoad.setVisibility(View.VISIBLE);
		txtLoad.setText("Tải dữ liệu thất bại ");
	}

	public void onEventMainThread(ErrorGetMoreVideoEvent e) {
		Log.e("", "ErrorGetMoreVideoEvent");
		listView.onLoadMoreComplete();
	}

	@Override
	public void onLoadMore() {
		// TODO Auto-generated method stub
		if (playlist.getNextPageToken() != null) {
			bgTask.getmoredata(playlist_id, playlist.getNextPageToken());
		} else {
			listView.onLoadMoreComplete();
		}

	}

	public void onEventMainThread(OnMenuItemClickEvent e) {
		Log.e("",
				"OnMenuItemClickEvent " + e.getPlaylist_id() + " "
						+ e.getTitle());
		String eplaylist_id = e.getPlaylist_id();
		if (this.playlist_id.equals(eplaylist_id)) {
		} else {
			llLoading.setVisibility(View.VISIBLE);
			reload.setVisibility(View.GONE);
			progressBar.setVisibility(View.VISIBLE);
			txtLoad.setText(getResources().getString(R.string.loading));
			loadData(eplaylist_id);
		}
	}

	@Override
	public void toogleFragement(String playlist_id, String playlist_name) {
		// TODO Auto-generated method stub
		if (this.playlist_id.equals(playlist_id)) {
		} else {
			llLoading.setVisibility(View.VISIBLE);
			reload.setVisibility(View.GONE);
			progressBar.setVisibility(View.VISIBLE);
			txtLoad.setText(getResources().getString(R.string.loading));
			loadData(playlist_id);
		}
	}

	public class MyAdapter extends BaseAdapter {
		private Context context;
		private ArrayList<Video> videos;
		Locale enUSLocale;

		public MyAdapter(Context context, ArrayList<Video> videos) {
			super();
			this.context = context;
			this.videos = videos;

			enUSLocale = new Locale("en", "us");
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return videos.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return arg0;
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return arg0;
		}

		@Override
		public View getView(int arg0, View arg1, ViewGroup arg2) {
			// TODO Auto-generated method stub
			if (arg1 == null) {
				arg1 = LayoutInflater.from(context)
						.inflate(R.layout.item, null);
			}
			ImageView img = (ImageView) arg1.findViewById(R.id.img);
			TextView title = (TextView) arg1.findViewById(R.id.title);
			TextView duration = (TextView) arg1.findViewById(R.id.duration);
			TextView view = (TextView) arg1.findViewById(R.id.view);
			imageLoader.displayImage(videos.get(arg0).high_url, img, options);
			title.setText(videos.get(arg0).title);
			if (videos.get(arg0) != null && videos.get(arg0).videoinfo != null
					&& videos.get(arg0).videoinfo.duration != null) {
				ArrayList<Integer> rs = getTime(videos.get(arg0).videoinfo.duration);
				String h = "";
				String m = "";
				String s = "";
				if (rs.get(0) < 10) {
					h = "0" + rs.get(0);
				} else {
					h = rs.get(0) + "";
				}

				if (rs.get(1) < 10) {
					m = "0" + rs.get(1);
				} else {
					m = rs.get(1) + "";
				}

				if (rs.get(2) < 10) {
					s = "0" + rs.get(2);
				} else {
					s = rs.get(2) + "";
				}

				duration.setText(h + ":" + m + ":" + s);
			}

			if (videos.get(arg0) != null && videos.get(arg0).videoinfo != null
					&& videos.get(arg0).videoinfo.viewCount != null)
				view.setText(
				// "Lượt xem: "+
				displayNumber(enUSLocale,
						Integer.valueOf(videos.get(arg0).videoinfo.viewCount))
						+ " views");
			arg1.setTag(videos.get(arg0).videoid);
			return arg1;
		}

	}

	public ArrayList<Integer> getTime(String duration) {
		int h = 0;
		int m = 0;
		int s = 0;
		ArrayList<Integer> rs = new ArrayList<Integer>();
		duration = duration.replace("PT", "");
		if (duration.contains("H")) {
			h = Integer
					.valueOf(duration.substring(0, duration.lastIndexOf("H")));
			duration = duration.substring(duration.indexOf("H") + 1,
					duration.length());
		}
		if (duration.contains("M")) {
			m = Integer
					.valueOf(duration.substring(0, duration.lastIndexOf("M")));
			duration = duration.substring(duration.indexOf("M") + 1,
					duration.length());
		}
		if (duration.contains("S")) {
			s = Integer
					.valueOf(duration.substring(0, duration.lastIndexOf("S")));
		}
		rs.add(h);
		rs.add(m);
		rs.add(s);
		return rs;

	}

	public String displayNumber(Locale currentLocale, int num) {

		NumberFormat numberFormatter;
		String quantityOut;

		numberFormatter = NumberFormat.getNumberInstance(currentLocale);
		quantityOut = numberFormatter.format(num);
		return quantityOut;
	}

}
